package be.pollsg1.login.servlets;

import java.io.IOException;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import be.pollsg1.service.UserServiceBusinessLocal;

/**
 * Servlet implementation class LoginServlet
 */
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	@EJB
	private UserServiceBusinessLocal userServices;
       

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		super.doGet(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		
		String error = null;
		
		if(username==null || username.isEmpty()){
			error = "Missing username";
		}
		else if(password==null || password.isEmpty()){
			error = "Missing password";
		}
		else if(!userServices.authentification(username, password)){
			error = "Login failed";
		}
		
		if(error!=null && !error.isEmpty()){
			request.setAttribute("error", error);
			request.getRequestDispatcher("/WEB-INF/views/login.jsp").forward(request, response);
		}
		else{
			request.getSession().setAttribute("loggedUser", username);
			response.sendRedirect(request.getContextPath());
		}
	}

}
